<?php 	
/**
 * 送真爱活动
 */  
class love {

	public function getIndex($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $actId=$param->actId;
	    $qId=$param->qId;
	    Session::switchCustomer(0);
	    $MplModel = M("miactivity_product_list");
	    $specModel = M("module_product_specification"); 
	    Session::switchCustomer($customerId);
		$weixinUserModel=M("user_weixin_info");
	    $result=self::getLoveConfig($param);
	    $mplwhere["actId"]=$actId;
	    $mplwhere["pro.isRemoved"]=0;
	    $mplwhere["pro.deleted"]=0;
	    $weixinInfo=$weixinUserModel->where("openid='$userName'")->find();
	    $mipro= $MplModel->alias('mpl')
	    ->field('pro.name,pro.id,pro.picUrl,pro.fixedPrice,pro.picUrl1,
	    	pro.discountedPrice,pro.fromCustomerId,pro.supportSpecification,
	    	pro.inventory,pro.inventoryCount')
	    ->where($mplwhere)
	    ->limit(0,1)
	    ->join("left join wx_module_product pro on pro.id=mpl.pId")
	    ->select();
	    foreach ($mipro as $key=>$val){  
	        // 获取规格
	        $pid=$val['id'];
	        if ($val["supportSpecification"] == 1) {
	            $arrFirstSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	            ->order("sepc.id")
	            ->getField("specificationName", true);
	        
	            if ($arrFirstSpec) {
	                $val["sizeUnit"] = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	        
	            }
	            if($arrFirstSpec){
					$val["size"] = json_encode($arrFirstSpec);
	            }

	            $arrSecSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	            ->getField("specificationName", true);
	        
	            if ($arrSecSpec) {
	                $val["colorUnit"] = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	            }
	            if($arrSecSpec) {
	            	$val["color"] = json_encode($arrSecSpec);
	            }
	            if ($val["inventory"] == 1) {
	            	if (isset($arr['availSku'])) {
	                    $availSku=$arr['availSku'];
	                }else{
	                    $params["pid"] = $val['id'];
	                    $params["arrFirstSpec"] = $arrFirstSpec;
	                    $params["arrSecSpec"] = $arrSecSpec;
	                    $availSku = Module::callModule('product', NULL, 'getProductInventory', $params);
	                }
	                $val["availSku"] = json_encode($availSku);
	            }
				if (!isset($val["availSku"])) {
					$val["availSku"] = json_encode(null);
				}
	        }
	        $result['pid']=$pid;
	        $mipro[$key]=$val;	
	        $newmipro[$pid]=$val;	  
	    }
	    $result['prodetail']=json_encode($newmipro);
	    $result['weixinInfo']=$weixinInfo;
	    $result['qId']=$qId;
	    //添加访问记录
	 //    $guid = $result["guid"];
		// $visitParam=new StdClass();
		// $visitParam->guid=$guid;
		// $visitParam->sId=$result["sId"];
		// $visitParam->fromGuid=$param->fromGuid;
		// $visitParam->miUId=$param->miUId;
		// $visitParam->fromPage="love_index";
		// $visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);
		// $result["visitId"]=$visitId;

	    if($mipro && count($mipro) > 0) {
	    	$result['pro']=$mipro[0]; 
	    }
	    if(!$result["code"]) {
	    	Output::instance()->module('love',"index")->object($result);
	    } else {
	    	Output::instance()->resultCode($result["code"],$result["msg"]);
	    }
	}
	public function getAnswer($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $regId=$param->regId;
	    Session::switchCustomer(0);
	    $MRegModel=M("miactivity_reglove");
	    Session::switchCustomer($customerId);
	    $regInfo=$MRegModel->alias("a")
	    ->where("a.promoterUserName='$userName' and a.id=$regId")
	    ->field("a.id,a.actId,a.fromCustomerId,a.promoterUserName,a.receiptorUserName
	    	,a.isProblem,a.question,a.promoterTime,a.receiptorTime,a.createTime,a.updateTime")
	    ->find();
	    $result=self::getLoveConfig($param);
	    $result["regInfo"]=$regInfo;
	    $result["regId"]=$regId;
	    if(!$result["code"]) {
	    	Output::instance()->module('love',"answer")->object($result);
	    } else {
	    	Output::instance()->resultCode($result["code"],$result["msg"]);
	    }
	}
	public function getList($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $MRegModel=M("miactivity_reglove");
	    Session::switchCustomer($customerId);

	    $order="a.createTime desc";

	    $regList=$MRegModel->alias("a")
	    ->join("left join wx_".$customerId."_user_weixin_info b on b.openid=a.promoterUserName")
	    ->field("b.headimgurl,b.nickname")
	    ->where("a.promoterUserName='$userName'")
	    ->order($order)
	    ->select();
	    $result=self::getLoveConfig($param);
	    $result["regList"]=$regList;
	    if(!$result["code"]) {
	    	Output::instance()->module('love',"list")->object($result);
	    } else {
	    	Output::instance()->resultCode($result["code"],$result["msg"]);
	    }
	}
	public function getLoveList($param,$start,$limit){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $actId=$param->actId;
	    Session::switchCustomer(0);
	    $MRegModel=M("miactivity_reglove");
	    Session::switchCustomer($customerId);
	    $order="a.createTime desc";
	    $pageStart=$start*$limit;
	    $regList=$MRegModel->alias("a")
	    ->join("left join wx_".$customerId."_user_weixin_info b on b.openid=a.promoterUserName")
	    ->join("left join wx_".$customerId."_user_weixin_info c on c.openid=a.receiptorUserName")
	    ->join("left join wx_miactivity_product_list d on d.actId=a.actId")
	    ->join("left join wx_module_product e on e.id=d.pId")
	    ->field("a.id,a.actId,a.fromCustomerId,a.promoterUserName,a.receiptorUserName
	    	,a.isProblem,a.question,a.promoterTime,a.receiptorTime,a.createTime,a.updateTime,b.headimgurl,b.nickname,c.headimgurl AS headimgurl1,c.nickname AS nickname1,e.name,e.picUrl")
	    ->limit($pageStart, $limit)
	    ->order($order)
	    ->where("a.promoterUserName='$userName' and a.actId=$actId")
	    ->select();

	    $mavres=new StdClass();
	    $mavres->count=$count;
	    $mavres->pageCount=getPageCount($count,$limit);
	    $mavres->list=$regList;
	    Output::instance()->object($mavres);
	}
	public function saveAnswer($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $regId=$param->regId;
	    Session::switchCustomer(0);
	    $regModel=M("miactivity_reglove");
	    Session::switchCustomer($customerId);
	    $time=date("Y-m-d H:i:s");
	    $addData=array(
	    	"actId"=>$param->actId,
	    	"fromCustomerId"=>$customerId,
	    	"promoterUserName"=>$userName,
	    	"receiptorUserName"=>"",
	    	"miUid"=>$param->miUId,
	    	"qId"=>$param->qId,
	    	"oid"=>$param->oid,
	    	"problem"=>"",
	    	"answer"=>"",
	    	"promoterTime"=>$time,
	    	"createTime"=>$time,
	    	"updateTime"=>$time
	    );
	    if($regId){
	    	$updateData=array(
	    		"isProblem"=>1,
		    	"question"=>$param->question,
		    	"answer"=>$param->answer
		    );
	    	$result=$regModel->where("id='$regId'")->save($updateData);
	    } else {
	    	$result=$regModel->add($addData);
	    	$regId=$result;
	    }
	   Log::write($regModel->getlastsql());
	    $out=new stdClass();
	    if($result!==false) {
	    	$out->code=0;
	    	$out->regId=$regId;
	    	Output::instance()->object($out);
	    } else {
	    	$out->code=1;
	    	$out->regId=$regId;
	    	Output::instance()->object(1,$out);
	    }
	}
	public function getAnswerInfo($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $fromRegId=$param->fromRegId;
	    $regId=$param->regId;
	    $answer=$param->answer;
		if($fromRegId){
			$regId=$fromRegId;
		}
	    Session::switchCustomer(0);
	    $regId=$param->regId;
	    $MRegModel=M("miactivity_reglove");
	    Session::switchCustomer($customerId);
	    $info=$MRegModel->alias("a")
	    ->where("a.id=$regId")
	    ->find();
	    if(!$info && count($info) <1){
	    	Output::instance()->resultCode(2,"记录不存在！");
	    	return;
	    }
	    if($info["answer"]!=$answer) {
	    	Output::instance()->resultCode(1,"答案错误！");
	    } else {
	    	Output::instance()->resultCode(0);
	    }
	}
	public function getView($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $regId=$param->regId; 
	    $fromRegId=$param->fromRegId;
		if($fromRegId){
			$regId=$fromRegId;
		}

	    Session::switchCustomer(0);
	    $MRegModel=M("miactivity_reglove");
	    Session::switchCustomer($customerId);
	    $result=self::getLoveConfig($param);
	    $info=$MRegModel->alias("a")
	    ->join("left join wx_".$customerId."_user_weixin_info b on b.openid=a.promoterUserName")
	    ->join("left join wx_".$customerId."_user_weixin_info c on c.openid=a.receiptorUserName")
	    ->field("a.id,a.actId,a.fromCustomerId,a.promoterUserName,a.receiptorUserName
	    	,a.isProblem,a.question,a.promoterTime,a.receiptorTime,a.createTime,a.updateTime
	    	,b.headimgurl,b.nickname,c.headimgurl AS headimgurl1,c.nickname AS nickname1")
	    ->where("a.id=$regId")
	    ->find();
	    $result["userInfo"]=$info;
	    $result["fromRegId"]=$fromRegId;
	    $result["regId"]=$regId;


	 //    //添加访问记录
	 //    $guid = $result["guid"];
		// $visitParam=new StdClass();
		// $visitParam->guid=$guid;
		// $visitParam->sId=$result["sId"];
		// $visitParam->fromGuid=$param->fromGuid;
		// $visitParam->miUId=$param->miUId;
		// $visitParam->fromPage="love_view";
		// $visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);
		// $result["visitId"]=$visitId;

	    if(!$result["code"]) {
	    	Output::instance()->module('love',"view")->object($result);
	    } else {
	    	Output::instance()->resultCode($result["code"],$result["msg"]);
	    }
	}
	public function saveReceiptor($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];

	    $regId=$param->regId;
	    $actId=$param->actId;
	    $fullName=$param->fullName;
	    $phone=$param->phone;
	    $address=$param->address;
	    

	    Session::switchCustomer(0);
	    $regId=$param->regId;
	    $MRegModel=M("miactivity_reglove");
	    $ProductOrderModel=M("module_product_order");
	    Session::switchCustomer($customerId);
	    $info=$MRegModel->alias("a")
	    ->where("a.id=$regId and a.actId=$actId")
	    ->find();
	    $out=new stdClass();
	    if($info["receiptorUserName"]!="") {
	    	$out->code=1;
	    	$out->msg="礼品已经被领取了";
	    	Output::instance()->object($out);
	    	return;
	    }
	    $MRegModel->startTrans();
	    $oid=$info["oid"];
	    $infoData["receiptorUserName"]=$userName;
	    $infoData["receiptorTime"]=date("Y-m-d H:i:s");
	    $result1=$MRegModel->where("id=$regId and actId=$actId")->save($infoData);
	    $orderData["fullName"]=$fullName;
	    $orderData["phone"]=$phone;
	    $orderData["address"]=$address;
	    $result2=$ProductOrderModel->where("id=$oid")->save($orderData);
	   
	    if($result1!==false && $result2!==false){
	    	$MRegModel->commit();
	    	$out->code=0;
	    	Output::instance()->object($out);
	    }else {
	    	$out->code=1;
	    	$out->msg="数据错误";
	    	Output::instance()->object($out);
	    }
	}
	public function getLoveConfig($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
		$userName=Session::$user['userName'];
		$actId=$param->actId;
		$uid = Session::$user['uid'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $actModel=M("miactivity");
	    Session::switchCustomer($customerId);
	    $fromUId=$param->fromUId;
		if($fromUId){
			$uid=$fromUId;
		}
	    $where["a.deleted"]=array('eq',0);
	    $where["a.status"]=array('eq',1);
	    $where["a.id"]=array('eq',$actId);
	    $where["a.fromCustomerId"]=array('eq',$customerId);
	    $curtime= date('Y-m-d 11:59:59');
		$where['a.startTime']=array('lt',$curtime);
		$where['a.endTime']=array('gt',$curtime);
	    $result=$actModel->alias("a")
	    ->join("inner join wx_mishare b on a.id=b.moduleId and b.module='miactivity'")
	    ->field("a.*,b.id as sId")
	    ->join("inner join wx_mishare_material c on c.sId=b.id")
	    ->where($where)
	    ->find();
		
		if($result){
	    	$json=json_decode($result["jsonstr"]);
	    	foreach ($json as $key => $value) {
	    		$va["src"]=$value->src;
	    		$va["info"]=$value->info;
	    		$va["type"]=$value->type;
	    		$va["key"]=$key;
	    		$jsonArr[$key]=$va;
	    	}
	    	$result["jsonstr"]=$jsonArr;
	    	
	    } else {
	    	$result["code"]=1;
	    	$result["msg"]="活动已结束!";
	    	return $result;
	    }
	    $Guid = new Guid();   
		$guid = $Guid->toString();//分享用的id
	    $result["fromUId"]=$uid;
	    $result["guid"]=$guid;
	    $result["actId"]=$actId;
	    return $result;
	}
}